<?php
require_once 'phpmoko/lib/common.php';

require_once 'phpmoko/externals/defaults.php';
require_once 'phpmoko/ui/Panel.php';
require_once 'phpmoko/utils/Browser.php';
require_once 'phpmoko/utils/Cache.php';
require_once 'phpmoko/utils/Console.php';
require_once 'phpmoko/utils/Cookie.php';

class RootPanel extends Panel
{
	private static $instance = NULL;
	private $title = null;
	private $language = null;
	private $links = array();
	private $linksFixed = array();
	private $jsFiles = array();
	private $jsFilesFixed = array();
	private $metaTags = array();
	private $metaTagsEquiv = array();
	private $errorMessages = array();
	private $warningMessages = array();
	private $debugMessages = array();
	private $infoMessages = array();
	private $keywords = array();
	private $jsCode = null;
	private $cssCode = null;
	private $onReadyJs = null;
	private $cache = true;
	private $googleAnalyticsId = null;
	private $favicon = null;
	private $combiFiles = false;
	private $showCookies = true;
	private $linkHeader = '';

	/**
	 *
	 * @var MySQL
	 */
	private $mysql = null;

	protected function __construct()
	{
		parent::__construct();

		Console::init();
	}

	function __destruct()
	{
		unset($this->mysql);
	}

	function openMySQL($server, $username, $password, $database_name, $persistent = true, $port = 3306)
	{
		require_once 'phpmoko/db/MySQL.php';
		$this->mysql = new MySQL($server, $username, $password, $database_name, $persistent, $port);
	}

	function addLinkHeader($title, $href, $rel, $type)
	{
		$this->linkHeader .= '<link rel="' . $rel . '" type="' . $type . '" title="' . $title . '" href="' . $href . '">';
	}

	/**
	 *
	 * @return MySQL
	 */
	function getMySQL()
	{
		if (!$this->mysql) {
			$callee = current(debug_backtrace());
			echo $callee['file'] . ' (' . $callee['line'] . ')<br><br>';
			echo 'Mysql not defined';
			die();
		}

		return $this->mysql;
	}

	function setGoogleAnalyticsId($id)
	{
		$this->googleAnalyticsId = $id;
	}

	function setShowLogo($enabled)
	{
		trigger_error("RootPanel::setShowLogo() is deprecated", E_USER_DEPRECATED);
	}

	function setCombiFiles($enabled)
	{
		$this->combiFiles = $enabled;
	}

	/**
	 *
	 * @deprecated Use Widget::getUniqueId()
	 */
	static function getUniqueId()
	{
		trigger_error("RootPanel::getUniqueId() is deprecated, please, use Widget::getUniqueId", E_USER_DEPRECATED);
		return Widget::getUniqueId();
	}

	/**
	 * gets the RootPanel
	 *
	 * @return RootPanel The current object
	 */
	static function get()
	{
		if (self::$instance == NULL)
			self::$instance = new RootPanel();

		return self::$instance;
	}

	function addCSSFile($href, $fixed = false)
	{
		include_once 'phpmoko/ui/Head/Link.php';

		$link = new Link();
		$link->setRel('stylesheet');
		$link->setType('text/css');
		$link->setHref($href);

		if ($fixed)
			$this->linksFixed[] = $link;
		else
			$this->links[] = $link;
	}

	function addErrorMessage($message)
	{
		$this->errorMessages[] = $message;
	}

	function addWarningMessage($message)
	{
		$this->warningMessages[] = $message;
	}

	function addDebugMessage($message)
	{
		$this->debugMessages[] = $message;
	}

	function addInfoMessage($message)
	{
		$this->infoMessages[] = $message;
	}

	function addKeyword($keyword)
	{
		if (!in_array($keyword, $this->keywords))
			$this->keywords[] = $keyword;
	}

	function setFavicon($href)
	{
		include_once 'phpmoko/ui/Head/Link.php';

		$this->favicon = new Link();
		$this->favicon->setRel('SHORTCUT ICON');
		$this->favicon->setHref($href);
	}

	function addJSFile($file, $fixed = false)
	{
		if ($fixed)
			$this->jsFilesFixed[] = $file;
		else
			$this->jsFiles[] = $file;
	}

	function addJSCode($code)
	{
		if ($this->jsCode != null)
			$this->jsCode .= ' ';

		$this->jsCode .= $code;
	}

	function addCSSCode($code)
	{
		if ($this->cssCode != null)
			$this->cssCode .= ' ';

		$this->cssCode .= $code;
	}

	function addJSOnReadyDocument($js)
	{
		if ($this->onReadyJs != null)
			$this->onReadyJs .= ' ';

		$this->onReadyJs .= $js;
	}

	function setTitle($title)
	{
		$this->title = $title;
	}

	function setLanguage($language)
	{
		$this->language = $language;
	}

	function setMetaTag($name, $content, $useName = true)
	{
		if ($useName)
			$this->metaTags[$name] = $content;
		else
			$this->metaTagsEquiv[$name] = $content;
	}

	function enableCache($enable)
	{
		$this->cache = $enable;
	}

	function enableShowCookiesMessage($mode)
	{
		$this->showCookies = $mode;
	}

	function getCookiesMessage()
	{
		if (!$this->showCookies)
			return '';

		$domain = Browser::getDomain();

		$cookie = new Cookie('COOKIES_POLICY');
		if ($cookie->getValue() == "true")
			return '';

		Cache::begin();
		?>
<div class="fbar">
	<div id="epbar">
		<style>
#epb-ok {
	background-color: #4d90fe;
	background-image: -webkit-linear-gradient(top, #4d90fe, #4787ed);
	border: 1px solid #3079ed;
	border-radius: 2px;
	color: #fff;
	cursor: default;
	display: inline-block;
	font-size: 11px;
	font-weight: bold;
	height: 20px;
	line-height: 20px;
	margin-right: 0px;
	min-width: 26px;
	outline: 0;
	padding: 0 8px;
	text-align: center;
	white-space: nowrap
}

#epb-ok:hover {
	background-color: #357ae8;
	background-image: -webkit-linear-gradient(top, #4d90fe, #357ae8);
	border: 1px solid #2f5bb7;
	border-bottom-color: 2f 5bb 7
}

#epb-ok:active {
	background: #357ae8;
	border: 1px solid #2f5bb7;
	border-top: 1px solid #2f5bb7;
	-webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, .3)
}

#epb-ok:focus {
	border: 1px solid #fff;
	border: 1px solid rgba(0, 0, 0, 0);
	-webkit-box-shadow: inset 0 0 0 1px #fff;
	outline: none
}

#epb-lm {
	color: #12c;
	cursor: pointer;
	margin-left: 6px;
	text-decoration: none;
}

#epb-lm:hover {
	text-decoration: underline
}

#epb-lm:visited {
	color: #609
}

#epb-lm:active {
	color: #dd4b39
}

#epbar {
	display: block;
}

#epbar #epb-notice {
	color: #666;
	display: inline-block;
	margin: 0px 1px 0 30px;
}

.fbar {
	clear: left font-family;
	background: #f2f2f2;
	border-top: 1px solid #e4e4e4;
	font-size: small;
	line-height: 40px;
	bottom: 0px;
	left: 0px;
	right: 0px;
	position: fixed;
	z-index: 100000;
	font-family: "lucida grande", tahoma, verdana, arial, sans-serif;
}
</style>
		<p id="epb-notice">Las cookies nos permiten ofrecer nuestros servicios. Al utilizar nuestros servicios, aceptas el uso que hacemos de las cookies.</p>
		<div title="Haz clic en Aceptar para ignorar este aviso." id="epb-ok" onmousedown="epbar.style.display='none';var exdate = new Date();exdate.setDate(exdate.getDate() + 365);var str = 'COOKIES_POLICY=true; domain=.<?=$domain;?>; path=/; expires=' + exdate.toUTCString();document.cookie = str;">Aceptar</div>
		<a target="_blank" href="http://www.phpmoko.com/help/cookies/index.php?domain=<?=$domain;?>" id="epb-lm" onmousedown="var exdate = new Date();exdate.setDate(exdate.getDate() + 365);var str = 'COOKIES_POLICY=true; domain=.<?=$domain;?>; path=/; expires=' + exdate.toUTCString();document.cookie = str;">Más información</a>
	</div>
</div>
<?php
		return Cache::end();
	}

	function toString()
	{
		$content = '';
		foreach ($this as $widget)
			$content .= $widget->toString();

		$str = '<!DOCTYPE html>';
		$str .= '<html';
		if ($this->language != null)
			$str .= ' lang="' . $this->language . '"';

		$str .= '>';

		$str .= '<head>';

		if ($this->title != null)
			$str .= '<title>' . $this->title . '</title>';
		else
			$str .= '<title>' . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"] . '</title>';

		$str .= '<meta charset="utf-8">';

		foreach ($this->metaTags as $name => $value)
			$str .= '<meta name="' . $name . '" content="' . $value . '" >';

		foreach ($this->metaTagsEquiv as $name => $value)
			$str .= '<meta http-equiv="' . $name . '" content="' . $value . '" >';

		if ($this->favicon != null)
			$str .= $this->favicon->toString();

		$cssfiles = '';
		$lasttime = gmmktime(1, 1, 1, 1, 1, 1980);
		for ($i = 0; $i < sizeof($this->links); $i++) {
			if ($this->combiFiles && ($this->links[$i]->getType() == "text/css")) {
				if ($cssfiles != "")
					$cssfiles .= "&amp;";

				$cssfiles .= $this->links[$i]->getHref();
				$date = filemtime('.' . $this->links[$i]->getHref());
				if ($lasttime < $date)
					$lasttime = $date;
			} else
				$str .= $this->links[$i]->toString();
		}

		$keyword = '';
		for ($i = 0; $i < sizeof($this->keywords); $i++) {
			if ($keyword != '')
				$keyword .= ',';
			$keyword .= $this->keywords[$i];
		}
		if ($keyword != '')
			$str .= '<meta name="keywords" content="' . $keyword . '">';

		if ($this->combiFiles && ($cssfiles != "")) {
			$link = new Link();
			$link->setRel('stylesheet');
			$link->setType('text/css');
			$link->setHref('/a/combi' . $cssfiles . '&amp;d=' . $lasttime);
			$str .= $link->toString();
		}

		for ($i = 0; $i < sizeof($this->linksFixed); $i++)
			$str .= $this->linksFixed[$i]->toString();

		for ($i = 0; $i < sizeof($this->jsFilesFixed); $i++)
			$str .= '<script src="' . $this->jsFilesFixed[$i] . '" type="text/javascript"></script>';

		$jsfiles = "";
		$lasttime = gmmktime(1, 1, 1, 1, 1, 1980);
		for ($i = 0; $i < sizeof($this->jsFiles); $i++) {
			$remote = (strpos($this->jsFiles[$i], "http://") === 0);

			if ($this->combiFiles && !$remote) {
				if ($jsfiles != "")
					$jsfiles .= "&amp;";

				$jsfiles .= $this->jsFiles[$i];
				$date = filemtime('.' . $this->jsFiles[$i]);
				if ($lasttime < $date)
					$lasttime = $date;
			} else
				$str .= '<script src="' . $this->jsFiles[$i] . '" type="text/javascript"></script>';
		}

		if ($this->combiFiles && ($jsfiles != ""))
			$str .= '<script src="/a/combi' . $jsfiles . '&amp;d=' . $lasttime . '" type="text/javascript"></script>';

		if ($this->jsCode != null)
			$str .= '<script type="text/javascript">' . $this->jsCode . '</script>';

		if ($this->cssCode != null)
			$str .= '<style type="text/css">' . $this->cssCode . '</style>';

		$str .= $this->linkHeader;

		$str .= '</head>';
		$str .= '<body>';

		if ($this->googleAnalyticsId != null) {
			$domain = Browser::getDomain();
			$str .= "<script>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '" . $this->googleAnalyticsId . "', '" . $domain . "'); ga('send', 'pageview');</script>";
		}

		$str .= $content;

		if ($this->errorMessages || $this->warningMessages || $this->debugMessages || $this->infoMessages) {
			// $str .= '<div style="position: fixed; bottom: 0px; right: 50%;; left: 50%; margin-left: -450px; width:900px">';
			$str .= '<div style="position: fixed; bottom: 0px; left: 0px">';
			if ($this->errorMessages) {
				$str .= '<div style="background-color: #FFCCCC; margin: 8px; padding: 8px; border: #DD7777 solid 1px; color: #AA0000">';
				$str .= '<b>Error Message</b><br><br>';
				for ($i = 0; $i < sizeof($this->errorMessages); $i++)
					$str .= $this->errorMessages[$i] . '<br>';
				$str .= '</div>';
			}

			if ($this->debugMessages) {
				$str .= '<div style="background-color: #D2E5C3; margin: 8px; padding: 8px; border: #84DCA8 solid 1px; color: #008800">';
				$str .= '<b>Debug Message</b><br><br>';
				for ($i = 0; $i < sizeof($this->debugMessages); $i++)
					$str .= $this->debugMessages[$i] . '<br>';
				$str .= '</div>';
			}

			if ($this->infoMessages) {
				$str .= '<div style="background-color: #C3D2E5; margin: 8px; padding: 8px; border: #84A8DC solid 1px; color: black">';
				$str .= '<b>Info Message</b><br><br>';
				for ($i = 0; $i < sizeof($this->infoMessages); $i++)
					$str .= $this->infoMessages[$i] . '<br>';
				$str .= '</div>';
			}

			if ($this->warningMessages) {
				$str .= '<div style="background-color: #FFFFCC; margin: 8px; padding: 8px; border: #F0C020 solid 1px; color: black">';
				$str .= '<b>Warning Message</b><br><br>';
				for ($i = 0; $i < sizeof($this->warningMessages); $i++)
					$str .= $this->warningMessages[$i] . '<br>';
				$str .= '</div>';
			}

			$str .= '</div>';
		}

		if ($this->onReadyJs != null)
			$str .= '<script> document.addEventListener(\'DOMContentLoaded\', function() { ' . $this->onReadyJs . ' });</script>';

		$str .= $this->getCookiesMessage();

		$str .= '</body>';
		$str .= '</html>';

		if ($this->cache) {
			require_once 'phpmoko/utils/Cache.php';
			$str = Cache::compressStream($str);
		}

		return $str;
	}
}

RootPanel::get();
?>